<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h2 class="time"></h2>
  <script>

    /*
    * timeStamp: 时间戳
    * fmtString: 格式化字符串
    *   yyyy-MM-dd hh:mm:ss
    *   yyyy年MM月dd日 hh时mm分ss秒
    *   yyyy/MM/dd hh:mm:ss
    *   yyyy.MM.dd hh:mm:ss
    */
    function formatTime(timeStamp, fmtString) {
      // 1.将时间戳转化为Date
      const date = new Date(timeStamp)
      // 2.获取年月日时分秒
      // const year = date.getFullYear()
      // const month = date.getMonth() + 1
      // const day = date.getDate()
      // const hour = date.getHours()
      // const minute = date.getMinutes()
      // const second = date.getSeconds()
      // 3.将年月日时分秒替换到fmtString中
      // const yearRe = /y+/
      // const mouthRe = /M+/

      // 定义正则和值之间的关系
      const dateO = {
        'y+': date.getFullYear(),
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      }
      for (const key in dateO) {
        const keyRe = new RegExp(key)
        if (keyRe.test(fmtString)) {
          const value = (dateO[key] + "").padStart(2, '0')
          fmtString = fmtString.replace(keyRe, value)
        }
      }
      return fmtString
    }

    const timeEl = document.querySelector('.time')
    const productJson = {
      name: 'iPhone',
      newPrice: 4999,
      oldPrice: 5999,
      endTime: 1629720000000
    }

    timeEl.textContent = formatTime(productJson.endTime, 'yyyy年MM月dd日 hh时mm分ss秒')


  </script>
</body>

</html>